#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

#define MAXARG 32

int main(int argc, char *argv[]) {
    char buf[512];
    char *args[MAXARG];
    int n, i;
    char c;

    if (argc < 2) {
        fprintf(2, "usage: xargs <command> [args...]\n");
        exit();
    }

    for (i = 1; i < argc; i++) {
        args[i-1] = argv[i];
    }
    int arg_idx = i-1;

    while ((n = read(0, &c, 1)) > 0) {
        static int buf_idx = 0;

        if (c == '\n' || buf_idx >= sizeof(buf)-1) {
            if (buf_idx == 0) continue; // 空行跳过

            buf[buf_idx] = '\0';
            buf_idx = 0;

            char *p = buf;
            while (*p != '\0' && arg_idx < MAXARG-1) {
                while (*p == ' ' || *p == '\t') p++;
                if (*p == '\0') break;

                args[arg_idx++] = p;

                while (*p != ' ' && *p != '\t' && *p != '\0') p++;
                if (*p != '\0') *p++ = '\0';
            }
            args[arg_idx] = 0;

            int pid = fork();
            if (pid == 0) {
                exec(args[0], args);
                fprintf(2, "xargs: exec %s failed\n", args[0]);
                exit();
            } else if (pid > 0) {
                wait();
                arg_idx = argc-1;
            } else {
                fprintf(2, "xargs: fork failed\n");
                exit();
            }
        } else {
            buf[buf_idx++] = c;
        }
    }

    if (n < 0) {
        fprintf(2, "xargs: read error\n");
        exit();
    }

    exit();
}